Understanding Maps
Understand maps in Go, including how to declare and access their values.
We'll cover the following
Introduction#
Maps are a collection of key-value pairs that a user can use to store some data and retrieve it with a key. In some languages, these are called dictionaries (Python) or hashes (Perl). In contrast to an array/slice, finding an entry in a map requires a single lookup versus iterating over the entire slice comparing values. With a large set of items, this can give us significant time savings.
Declaring a map#
There are several ways to declare a map. Let's first look at using make:
The example just shared creates a map with string keys and stores data that is an int type. 10 signifies that we want to pre-size for 10 entries. The map can grow beyond 10 entries, and the 10 can be omitted.
Another way of declaring a map is by using a composite literal:
This creates a map with string keys and stores the string data. We also pre-populate the entry with two key-value entries. We can omit the entries to have an empty map.
Accessing values#
We can retrieve a value as follows:
This assigns the chevy value to carMake. But what happens if the key isn't in the map? In that case, we'll receive the zero value of the data type:
The preceding code will print an empty string, which is the zero value of the string type that is used as a value in our map. We can also detect if the value is in the map:
Here we assign two values. The first (carMake) is the data stored in the key (or zero value if not set), and the second (ok) is a boolean that indicates if the key was found.
Adding new values#
Adding a new key-value pair or updating a key's value is done the same way:
Now that we can change a key-value pair, let's look at extracting values from a map.
Extracting all values#
To extract values from a map, we can use the for...range syntax that we used for slices. There are a few key differences with maps:
Instead of an index, we'll get the map's key.
Maps have a non-deterministic order.
Non-deterministic order means that iterating over the data will return the same data but not in the same order. Let's print out all the values in our carMake map:
Note: Similar to a slice, if we don't need the key, we may use
_instead. If we simply want the keys, we can omit the valuevalvariable, such as forkey := range modelToMake.
In this lesson, we have learned about the map type, how to declare them, add values to them, and finally how to extract values from them.
Using Arrays and Slices
Challenge: Find Repeating Words in a Sentence